<script setup>
import HeaderMenuWhite from "~/components/base/HeaderMenuWhite.vue";
import Form1 from "~/components/editUser/Form1.vue";
import Form2 from "~/components/editUser/Form2.vue";
import Form3 from "~/components/editUser/Form3.vue";
import Form4 from "~/components/editUser/Form4.vue";
import { onMounted, ref } from "vue";
import { ElMessage } from "element-plus";
import { getShopUserInfo, submitShopApply, getMyShopInfo } from "~/api/user.js";
import { listByIds } from "~/api/oss.js";
import { useRouter } from "vue-router";

const router = useRouter();
const form1 = ref();
const form2 = ref();
const form3 = ref();
const form4 = ref();
const submitting = ref(false);

const next = async () => {
  if (submitting.value) {
    return;
  }

  try {
    submitting.value = true;
    
    // 验证个人信息
    await form1.value.checkForm();
    
    // 验证专业技能
    const form2Value = await form2.value.skill();
    let checkForm2 = true;
    for (let i = 0; i < form2Value.length; i++) {
      const form2Item = form2Value[i];
      if (!form2Item.goodsTypeId || !form2Item.experienceYear) {
        checkForm2 = false;
        continue;
      }
    }
    if (!checkForm2) {
      ElMessage.warning("请完善专业技能信息");
      submitting.value = false;
      return;
    }
    
    // 验证教育背景
    const from3Value = form3.value.education;
    let checkForm3 = true;
    for (let i = 0; i < from3Value.length; i++) {
      const form3Item = from3Value[i];
      if (
        !form3Item.type ||
        !form3Item.schoolName ||
        !form3Item.graduateTime ||
        form3Item.fullTime === ""
      ) {
        checkForm3 = false;
        continue;
      }
    }
    if (!checkForm3) {
      ElMessage.warning("请完善教育背景信息");
      submitting.value = false;
      return;
    }
    
    // 验证店铺信息
    await form4.value.checkForm();
    
    // 提交数据阶段 - 这里才显示网络错误
    try {
      // 获取表单数据（现在通过 getter 直接获取）
      const form1Data = form1.value.formData;
      const form4Data = form4.value.formData;
      
      // 处理地址数据
      // form1Data.address 是地区选择器数组 ["北京市", "东城区", "朝阳区"]
      // form1Data.addressDetails 是详细地址字符串
      let province = "";
      let city = "";
      let county = "";
      
      if (Array.isArray(form1Data.address)) {
        province = form1Data.address[0] || "";
        city = form1Data.address[1] || "";
        county = form1Data.address[2] || "";
      }
      
      // 检查是否有主营技能
      const hasMainSkill = form2Value.some(skill => skill.isMain === 1);
      if (!hasMainSkill) {
        ElMessage.warning("请至少设置一个主营技能");
        submitting.value = false;
        return;
      }
      
      // 构建开店申请数据（按照新API格式）
      const shopApplyData = {
        // 用户基本信息
        nickName: form1Data.nickName,
        avatar: form1Data.avatar,
        wxchat: form1Data.wxchat,
        province: province,
        city: city,
        county: county,
        address: form1Data.addressDetails || "",  // 详细地址
        
        // 技能信息（必须有至少一个主营技能）
        skills: form2Value,
        
        // 教育背景（可选）
        educations: from3Value,
        
        // 店铺信息
        shopName: form4Data.shopName,
        shopType: form4Data.shopType,
        isSelf: form4Data.isSelf,
        introduction: form4Data.introduction,
      };
      
      // 使用新的开店申请API
      const result = await submitShopApply(shopApplyData);
      
      if (result.code === 200) {
        ElMessage.success("开店申请提交成功");
        await router.push("/realName");
      } else {
        ElMessage.error(result.msg || "提交失败，请重试");
      }
    } catch (error) {
      // 只有网络请求失败时才显示网络错误
      console.error("提交失败:", error);
      ElMessage.error("提交失败，请检查网络或稍后重试");
    }
  } catch (e) {
    // 表单验证失败 - 不显示额外错误提示
    // Element Plus 的表单验证会自动显示具体字段的错误
  } finally {
    submitting.value = false;
  }
};

onMounted(() => {
  getInfo();
});

// 初始化获取用户信息，回填
const info = ref({});
const getInfo = async () => {
  try {
    // 1. 获取用户基本信息（个人信息 - Form1）
    const userRes = await getShopUserInfo();
    if (userRes.code !== 200) {
      ElMessage.error(userRes.msg || '获取用户信息失败');
      return;
    }
    
    // 初始化个人基本信息
    info.value = userRes.data || {};
    
    // 2. 根据 hasShop 字段判断是否需要获取店铺信息
    if (info.value.hasShop === true) {
      // 已开店，获取店铺信息（店铺、技能、教育背景 - Form2、Form3、Form4）
      try {
        const shopRes = await getMyShopInfo();
        if (shopRes && shopRes.code === 200 && shopRes.data) {
          // 合并店铺信息到 info 中
          // 保留个人基本信息，补充店铺相关信息
          info.value = {
            ...info.value,           // 个人基本信息（昵称、头像、地址等）
            ...shopRes.data,         // 店铺信息（店铺名称、技能、教育背景等）
          };
        }
      } catch (err) {
        console.error('获取店铺信息失败:', err);
        ElMessage.error('获取店铺信息失败，请刷新重试');
      }
    }
    // 如果 hasShop 为 false，说明未开店，只使用基本用户信息即可
    
    // 3. 处理地址数据映射
    // province、city、county 组合成地区选择器数组
    // address 映射到 addressDetails（详细地址）
    if (info.value.province || info.value.city || info.value.county) {
      const addressArray = [];
      if (info.value.province) addressArray.push(info.value.province);
      if (info.value.city) addressArray.push(info.value.city);
      if (info.value.county) addressArray.push(info.value.county);
      
      // 保存原始的详细地址
      const detailAddress = info.value.address;
      
      // 将地区数组赋值给 address（地区选择器使用）
      info.value.address = addressArray;
      
      // 将原始的 address 赋值给 addressDetails（详细地址输入框使用）
      info.value.addressDetails = detailAddress || '';
    }
    
    // 4. 处理头像：如果是 ossId，转换为 URL
    if (info.value.avatar && !info.value.avatar.includes('http')) {
      try {
        const ossRes = await listByIds(info.value.avatar);
        if (ossRes.data && ossRes.data.length > 0) {
          info.value.avatar = ossRes.data[0].url;
        }
      } catch (err) {
        console.error('获取头像URL失败:', err);
      }
    }
  } catch (e) {
    console.error('获取用户信息失败:', e);
    ElMessage.error('获取用户信息失败，请刷新重试');
  }
};

//
const exit = () => {
  router.push("/login");
};
</script>

<template>
  <div class="edit-user">
    <HeaderMenuWhite :bgColor="'white'" :showSearch="false" />
    <div class="form-items">
      <Form1 ref="form1" :info="info" />
      <Form2 ref="form2" :info="info" />
      <Form3 ref="form3" :info="info" />
      <Form4 ref="form4" :info="info" />
    </div>
    <div class="btns" v-if="step !== 0">
      <el-button class="close" :disabled="submitting" @click="exit">退出</el-button>
      <el-button class="next" :loading="submitting" :disabled="submitting" @click="next">
        {{ submitting ? '提交中...' : '下一步' }}
      </el-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.edit-user {
  background: #f9f9f9;
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.form-items {
  flex: 1;
  height: calc(100vh - 80px);
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  padding-top: 80px;
  
  @media (max-width: 768px) {
    padding-top: 60px;
  }
  
  @media (max-width: 480px) {
    padding-top: 56px;
  }
}

.btns {
  display: flex;
  height: 80px;
  align-items: center;
  justify-content: center;
  background: #fff;

  .close {
    width: 92px;
    height: 36px;
    background: #ffffff;
    border-radius: 8px 8px 8px 8px;
    border: 1px solid rgba(25, 30, 40, 0.08);
    color: rgba(25, 30, 40, 0.6);
  }

  .next {
    width: 92px;
    height: 36px;
    background: #1dbf73;
    border-radius: 8px 8px 8px 8px;
    color: #fff;
  }
}
</style>

<style>
.edit-user .el-input__wrapper {
  height: 48px;
  border-radius: 8px 8px 8px 8px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  box-shadow: none;
}
</style>